import {
    createRouter,
    createWebHistory
} from "vue-router";
import {
    adminRouter,
    supersRouter,
    shareRouter
} from "./routes.js"

import {
    useUserStore
} from "@/store/useUserStore.js"
import {
    createPinia,
    storeToRefs
} from "pinia"

// 创建路由实例
const router = createRouter({
    history: createWebHistory(),
    linkExactActiveClass: "exact-active",
    linkActiveClass: "active",
    routes: shareRouter,
});
const pinia = createPinia();
let starte = true
router.beforeEach((to, from, next) => {
    const store = useUserStore();
    const {
        userInfo
    } = storeToRefs(store)

    if (userInfo.value.authentication === 1 && starte) {
        
        for (const item of adminRouter) {
            router.addRoute("home", item)
        }
        next({
            ...to,
            replace: true
        })
        starte = false
    } else if(userInfo.value.authentication === 0 && starte){

        for (const item of supersRouter) {
            router.addRoute("home", item)
        }
        
        next({
            ...to,
            replace: true
        })
        starte = false
    }
    // 如果没有teken，且访问的是非登录页,拦截到登录，其他情况正常放行
    if (!sessionStorage.getItem("token") && to.path !== '/') {
        next("/")
    } else {
        next()
    }




})
export default router